package com.jus.player.fragment.play;

import static com.jus.player.api.OkHttpHelper._DATA;
import static com.jus.player.api.OkHttpHelper._RECORD;

import android.annotation.SuppressLint;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson2.JSONObject;
import com.google.android.gms.common.util.CollectionUtils;
import com.jus.player.R;
import com.jus.player.adapter.play.VideoListAdaptor;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.config.AppConfig;
import com.jus.player.entity.SpacesItemDecoration;
import com.jus.player.entity.VideoEntity;
import com.jus.player.fragment.BaseFragment;
import com.jus.player.util.CommonUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VideoListFragment extends BaseFragment {

    private final List<VideoEntity> videoList = new ArrayList<>();
    private final Long mCategoryId;
    private int pageNo = 1;
    private VideoListAdaptor adaptor;

    public VideoListFragment(Long categoryId) {
        this.mCategoryId = categoryId;
    }

    public static VideoListFragment newInstance(Long categoryId) {
        return new VideoListFragment(categoryId);
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_video_list;
    }

    @Override
    protected void initView() {
        RecyclerView recyclerView = findViewById(R.id.video_list_recyclerView);
        int spanCount = AppConfig.INT_3;
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), spanCount));
        // 设置间隙装饰
        recyclerView.addItemDecoration(
                new SpacesItemDecoration(spanCount, 20, false));
        adaptor = new VideoListAdaptor();
        adaptor.setVideoList(videoList);
        recyclerView.setAdapter(adaptor);// 设置适配器

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 检查是否滚动到底部
                if (!recyclerView.canScrollVertically(AppConfig.INT_1)) {
                    // 触发加载更多数据的逻辑
                    pageNo++;
                    getVideoList(false, mCategoryId);
                }
            }
        });
    }

    @Override
    protected void initData() {
        getVideoList(true, mCategoryId);
    }

    @Override
    protected boolean isLazyLoad() {
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!videoList.isEmpty()) {
            pageNo = 1;
            getVideoList(true, mCategoryId);
        }
    }

    private void getVideoList(boolean isRefresh, Long categoryId) {

        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", ApiConfig.PAGE_30_SIZE + "");
        map.put("categoryId", categoryId + "");
        OkHttpHelper.getInstance(requireActivity()).getAsync(ApiConfig.VIDEO_LIST, map,
                new OkHttpHelper.HttpCallback() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onSuccess(String res) {
                        handleResData(res, isRefresh);
                        if (getActivity() != null) {
                            getActivity().runOnUiThread(() -> {
                                adaptor.notifyDataSetChanged();
                            });
                        }
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        CommonUtils.showToastAsync(requireActivity(), e.getMessage());
                    }
                });
    }

    private void handleResData(String resData, boolean isRefresh) {
        JSONObject jo = JSONObject.parseObject(resData);
        List<VideoEntity> resList = jo.getJSONObject(_DATA).getList(_RECORD, VideoEntity.class);
        if (resList == null || resList.isEmpty()) {
            return;
        }
        for (VideoEntity v : resList) {
            List<JSONObject> typeList = v.getTypeList();
            if (!CollectionUtils.isEmpty(typeList)) {
                for (JSONObject t : typeList) {
                    if (t.getInteger("type") == 0) {
                        v.setLastEpisode(t.getInteger("lastEpisode"));
                    }
                }
            }
        }
        if (isRefresh) {
            videoList.clear();
        }
        videoList.addAll(resList);
    }

}